//
//  CMCLocation.m
//  MobHuntApp
//
//  Created by Nong Trung Nghia on 10/11/12.
//  Copyright (c) 2012 CMC Software. All rights reserved.
//

#import "CMCLocation.h"



@interface CLLocationManagerBLockExt : CLLocationManager <CLLocationManagerDelegate>

@property (nonatomic, copy) CMCLocationSuccessBlock success;
@property (nonatomic, copy) CMCLocationFailureBlock failure;
@property (nonatomic) BOOL updated;

@end

@implementation CLLocationManagerBLockExt
@synthesize success=_success;
@synthesize failure=_failure;
@synthesize updated=_updated;
-(id)initWithSuccess:(CMCLocationSuccessBlock)successBlock failure:(CMCLocationFailureBlock)failureBlock
{
    self = [super init];
    if (self)
    {
        self.success = successBlock;
        self.failure = failureBlock;
        self.delegate = self;
        [self startUpdatingLocation];
        self.updated=NO;
    }
    return self;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [self stopUpdatingLocation];

    if (_success && !_updated)
    {
        _updated=YES;
//        dispatch_retain(_success);
//        dispatch_async(dispatch_get_main_queue(), ^{
        _success(newLocation);
     
//        });
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    [self stopUpdatingLocation];
    if (self.failure && !_updated) {
        _updated=YES;
//        dispatch_async(dispatch_get_main_queue(), ^{
        self.failure(error);

//        });
    }
}


@end

@implementation CMCLocation

+(void)getCurrentLocationDidSuccess:(CMCLocationSuccessBlock)successBlock failure:(CMCLocationFailureBlock)failureBlock
{
    CLLocationManagerBLockExt *manager = [[CLLocationManagerBLockExt alloc] initWithSuccess:successBlock failure:failureBlock];
    manager=nil;
}

#pragma mark -


@end
